<template>
  <div style="margin-top:0">
    <!--订单执行-->
    <div class="data-title">
        <div class="title-left">
           <div class="title-item" :class="{'choose':listQuery1.tab == 'my'}"  @click="changeTab1('my')" v-if="myStockListAnalysis">个人订单执行与库存</div>
           <div class="title-item" :class="{'choose':listQuery1.tab == 'all'}" @click="changeTab1('all')" v-if="allStockListAnalysis">全部订单执行与库存</div>
        </div>
        <div class="title-right">
          <el-select @change="handleSearchList1" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery1.goodsClass" >
            <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
          </el-select>
          <el-input size="mini" @change="handleSearchList1" placeholder="请输入厂家" v-if="listQuery1.goodsClass" clearable style="width:150px;margin-right: 10px"  v-model="listQuery1.brandName"></el-input>
          <el-select @change="handleSearchList1" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery1.kingGoodsId" filterable>
            <el-option
              v-for="item in goodsList"
              :key="item.kingId"
              :label="item.goodsSn"
              :value="item.kingId">
            </el-option>
          </el-select>
            <el-select size="mini"
                       collapse-tags
                       v-model="listQuery1.userIds" clearable v-if="listQuery1.tab != 'my'"
                       @change="handleSearchList1"  placeholder="请选择人员" multiple>
              <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
              </el-option>
            </el-select>
        </div>
     </div>
    <div class="order-block">
        <div class="data-block order-num pums" style="width:620px">
          <div class="order-num-item">
             <div class="num-item-top">可用库存量 <i class="el-icon-caret-right"></i></div>
             <div class="num-item-bottom" @click="topage('searchStock')">
                <div class="bottom-icon"><img src="https://pic.moresu.com/Fp3LU4kVRA0Zt6LBEuFgXz8wLBka" style="width:26px"/></div>
                <div class="bottom-num">{{ enableAllNum }}<span class="span">吨</span></div>
             </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">实际库存量 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fp3LU4kVRA0Zt6LBEuFgXz8wLBka" style="width:26px"/></div>
              <div class="bottom-num">{{ stockAllNum }}<span class="span">吨</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">待入库量 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FkjbPQKcWZ9ez_i1TWZcVk_2knHi"/></div>
              <div class="bottom-num">{{ unStockInAllNum }}<span class="span">吨</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">销量在订量 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fit-WZdNKBaYnuZVxktjCwmvmSkn" style="width:20px"/></div>
              <div class="bottom-num">{{ unSendAllNum }}<span class="span">吨</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">平均成本价 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fis0kE6bAAJafsJIW_lBnMtGOe41"/></div>
              <div class="bottom-num">{{ averagePriceAll }}<span class="span">元</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">库存成本 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fis0kE6bAAJafsJIW_lBnMtGOe41"/></div>
              <div class="bottom-num">{{ stockAllAmount }}<span class="span">元</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">库存盈亏 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FjiHRzY90M5wXaRylY2nLK6rJnwo"/></div>
              <div class="bottom-num">{{ lossAllAmount }}<span class="span">元</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">未入库完成订单 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('purchaseContract',)">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FsKGTVwJF2nh8zWAzRjSW1VariVe"/></div>
              <div class="bottom-num">{{ unFinishedOrderCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item red">
            <div class="num-item-top">未付款 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('purchaseContract0')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FvHZDRevhdYJKzCpUwNCthOIgutR"/></div>
              <div class="bottom-num">{{ unPaidOrderCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">部分付款 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('purchaseContract1')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FgW3h2P1YY9f6oQfhrJ3SxmzWxCM"/></div>
              <div class="bottom-num">{{ partPaidOrderCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">部分入库量 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('searchStock')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fp3LU4kVRA0Zt6LBEuFgXz8wLBka" style="width:26px"/></div>
              <div class="bottom-num">{{ partInStockNum }}<span class="span">吨</span></div>
            </div>
          </div>
        </div>
        <div class="data-block order-table" style="width:calc(100% - 620px)">
          <el-table :data="list1"  style="width: 100%;" class="data-table" :height="340" v-loading="listLoading1">
            <el-table-column
              align="center"
              label="采购员"
              min-width="100">
              <template slot-scope="scope">{{scope.row.chargeName}}</template>
            </el-table-column>
            <el-table-column
              align="center"
              label="可用库存量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.enableNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="实际库存量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.stockNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="待入库量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.unStockInNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="销售在订量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.unSendNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="平均成本价"
              min-width="100">
              <template slot-scope="scope">
               {{scope.row.averagePrice}}
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              label="库存成本"
              min-width="100">
              <template slot-scope="scope">
               {{scope.row.stockAmount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="库存盈亏"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.lossAmount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="未入库完成订单"
              min-width="180">
              <template slot-scope="scope">
                {{scope.row.unFinishedOrderCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="未付款"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.unPaidOrderCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="部分付款"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.partPaidOrderCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="部分入库量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.partInStockNum}}
              </template>
            </el-table-column>
          </el-table>
        </div>
    </div>

    <!--销售情况&目标-->
    <el-row style="margin-top:10px" :gutter="8">
      <el-col :span="12">
        <div class="data-title">
          <div class="title-left">
            <div class="title-item" :class="{'choose':listQuery2.tab == 'my'}" v-if="pMySaleOrderSummary" @click="changeTab2('my')">采购-个人销量</div>
            <div class="title-item" :class="{'choose':listQuery2.tab == 'all'}"  v-if="pAllSaleOrderSummary" @click="changeTab2('all')">采购-公司销量</div>
          </div>
          <div class="title-right">
            <el-select size="mini" v-model="listQuery2.userIds"
                       collapse-tags
                       clearable v-if="listQuery2.tab != 'my'" @change="getSaleSum"
                       placeholder="请选择人员" multiple>
              <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="sum-block" >
           <el-row :gutter="5" v-if="saleSum">
             <el-col :span="6">
               <div class="sum-block-item">
                  <div class="sum-title">今日统计</div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.todayOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.todayShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.todayShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>
             <el-col :span="6">
               <div class="sum-block-item">
                 <div class="sum-title">本周统计</div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.weekOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.weekShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.weekShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>
             <el-col :span="6">
               <div class="sum-block-item">
                 <div class="sum-title">本月统计</div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.monthOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.monthShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.monthShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>
             <el-col :span="6">
               <div class="sum-block-item">
                 <div class="sum-title">本年统计</div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.yearOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.yearShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.yearShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>

           </el-row>
        </div>
      </el-col>

      <el-col :span="12">
        <div class="data-title">
          <div class="title-left">
            <div class="title-item" :class="{'choose':listQuery3.tab == 'my'}" v-if="pMySaleTargetSummary" @click="changeTab3('my')">采购-个人目标达成</div>
            <div class="title-item" :class="{'choose':listQuery3.tab == 'all'}"  v-if="pAllSaleTargetSummary" @click="changeTab3('all')">采购-公司目标达成</div>
          </div>
          <div class="title-right">
            <el-select size="mini" v-model="listQuery3.userIds"
                       clearable collapse-tags
                       v-if="listQuery3.tab != 'my'" @change="getSaleTarget"  placeholder="请选择人员" multiple>
              <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="target-block" v-if="saleTarget">
          <el-row :gutter="5" >
             <el-col :span="12">
                <div class="target-item">
                  <div class="target-left">
                     <div class="target-label">本月销量目标</div>
                     <div class="target-num">{{ saleTarget.monthOrderNumTarget}}<span class="unit">吨</span></div>
                     <div class="target-differ" :class="{'green':saleTarget.monthOrderNumDiff >= 0,'red':saleTarget.monthOrderNumDiff < 0}">目标差额<span class="unit">{{saleTarget.monthOrderNumDiff<0 ? '↓ ':'↑ '}}{{Math.abs(saleTarget.monthOrderNumDiff)}}吨</span></div>
                  </div>
                  <div class="target-right">
                    <el-progress type="circle" :percentage="saleTarget.monthOrderNumDiffRate" :width="88" color="#00b8f2" :format="formatProgress"></el-progress>
                  </div>
                </div>
             </el-col>
             <el-col :span="12">
              <div class="target-item purple">
                <div class="target-left">
                  <div class="target-label">本月毛利目标</div>
                  <div class="target-num">{{ saleTarget.monthShipProfitTarget }}<span class="unit">元</span></div>
                  <div class="target-differ" :class="{'green':saleTarget.monthShipProfitDiff >= 0,'red':saleTarget.monthShipProfitDiff < 0}">目标差额<span class="unit">{{saleTarget.monthShipProfitDiff<0 ? '↓ ':'↑ '}}{{ Math.abs(saleTarget.monthShipProfitDiff) }}元</span></div>
                </div>
                <div class="target-right">
                  <el-progress type="circle" :percentage="saleTarget.monthShipProfitDiffRate" :width="88" color="#8252e9"></el-progress>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="5" style="margin-top: 8px">
            <el-col :span="12">
              <div class="target-item bule">
                <div class="target-left">
                  <div class="target-label">本年销量目标</div>
                  <div class="target-num">{{ saleTarget.yearOrderNumTarget }}<span class="unit">吨</span></div>
                  <div class="target-differ" :class="{'green':saleTarget.yearOrderNumDiff >= 0,'red':saleTarget.yearOrderNumDiff < 0}">目标差额<span class="unit">{{saleTarget.yearOrderNumDiff<0 ? '↓ ':'↑ '}}{{Math.abs(saleTarget.yearOrderNumDiff)}}吨</span></div>
                </div>
                <div class="target-right">
                  <el-progress type="circle" :percentage="saleTarget.yearOrderNumDiffRate" :width="88" color="#3860f2"></el-progress>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="target-item green">
                <div class="target-left">
                  <div class="target-label">本年毛利目标</div>
                  <div class="target-num">{{ saleTarget.yearShipProfitTarget }}<span class="unit">元</span></div>
                  <div class="target-differ" :class="{'green':saleTarget.yearShipProfitDiff >= 0,'red':saleTarget.yearShipProfitDiff < 0}">目标差额<span class="unit">{{saleTarget.yearShipProfitDiff<=0 ? '↓ ':'↑ '}}{{ Math.abs(saleTarget.yearShipProfitDiff) }}元</span></div>
                </div>
                <div class="target-right">
                  <el-progress type="circle" :percentage="saleTarget.yearShipProfitDiffRate" :width="88" color="#45b369"></el-progress>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>

    </el-row>

    <!--人员销售*人员毛利*品类销售-->
    <div class="data-title" style="margin-top: 10px">
      <div class="title-left">
        <div class="title-item" :class="{'choose':curIndex4 ==1}" @click="changeTab4(1)" v-if="pUserOrderNumAnalysis">采购-人员销量</div>
        <div class="title-item" :class="{'choose':curIndex4 ==2}" @click="changeTab4(2)" v-if="pUserProfitAnalysis">采购-人员毛利</div>
        <div class="title-item" :class="{'choose':curIndex4 ==3}" @click="changeTab4(3)">采购-品类销量</div>
        <div class="title-item" :class="{'choose':curIndex4 ==4}" @click="changeTab4(4)">采购-品类毛利</div>
      </div>
      <div class="title-right">
        <el-radio-group v-model="radio" size="mini" style="margin-right: 10px" v-if="curIndex4 == 2 || curIndex4 == 4" @change="getChartsData">
          <el-radio-button label="1">吨毛利</el-radio-button>
          <el-radio-button label="2">总毛利</el-radio-button>
        </el-radio-group>
        <el-date-picker
          @change="getChartsData"
          style="width:150px;margin-right: 10px"
          size="mini"
          value-format="yyyy-MM"
          placeholder="请选择月份"
          v-model="listQuery4.month"
          type="month"
          align="right">
        </el-date-picker>
        <el-select @change="getChartsData" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-if="curIndex4 != 3 && curIndex4 != 4" v-model="listQuery4.goodsClass" >
          <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
        </el-select>
        <el-input size="mini" @change="getChartsData" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px" v-if="curIndex4 != 3 && curIndex4 != 4 && listQuery4.goodsClass" v-model="listQuery4.brandName"></el-input>
        <el-select size="mini" v-model="listQuery4.userIds"
                   clearable collapse-tags
                   @change="getChartsData"  placeholder="请选择人员" multiple>
          <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
          </el-option>
        </el-select>

      </div>
    </div>
    <div class="data-block" style="margin-top: 10px">
      <div id="myChart" style="height: 300px" class="charts-div" v-loading="chartLoading"></div>
    </div>


  </div>
</template>

<script>
import {saleOrderExeAnalysis,saleOrderExeAnalysisList,psaleOrderSummary,psaleTargetSummary,puserOrderNumAnalysis,
  puserProfitAnalysis,puserPerProfitAnalysis,pclassOrderNumAnalysis,pclassProfitAnalysis,pclassPerProfitAnalysis,stockListAnalysis} from '@/api/data.js'
import echarts from "echarts";
import {formatDate} from '@/utils/date';
import store from '@/store';
import {mapGetters} from "vuex";
const defaultListQuery={
  tab: "" ,  //我的：my  ， 公司：all
  userIds:[],
  "goodsClass" : "", //品类
  "brandName" : "", //厂家
  kingGoodsId:''
};

const defaultListQuery2={
  tab: "" ,  //我的：my  部门:department  事业部:group  公司：all
  userIds:[],
};

const defaultListQuery3={
  tab: "" ,  //我的：my  部门:department  事业部:group  公司：all
  userIds:[],
};

const defaultListQuery4={
  "userIds"   : [],   //人员ID
  "month" : "",   //统计月份
  "goodsClass" : "", //品类
  "brandName" : "" //厂家
};

  export default {
    name: 'pumsData',
    data() {
      return {
        roles:store.getters.roles ? store.getters.roles : [],
        pickerOptions: {
          shortcuts: [{
            text: '今日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '本周',
            onClick(picker) {
              const now = new Date();
              // 获取今天是本周的第几天（0代表星期日，1代表星期一，...，6代表星期六）
              const dayOfWeek = now.getDay();
              // 计算本周第一天（星期一）的日期
              const startOfWeek = new Date(now);
              startOfWeek.setDate(now.getDate() - dayOfWeek + 1); // 调整为星期一
              // 计算本周最后一天（星期日）的日期
              const endOfWeek = new Date(startOfWeek);
              endOfWeek.setDate(startOfWeek.getDate() + 6); // 从星期一开始加6天得到星期日
              picker.$emit('pick', [startOfWeek, endOfWeek]);
            }
          }, {
            text: '本月',
            onClick(picker) {
              const now = new Date();
              // 获取当前月份和年份
              const month = now.getMonth();
              const year = now.getFullYear();
              // 计算本月第一天的日期
              const startOfMonth = new Date(year, month, 1);
              // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
              const startOfNextMonth = new Date(year, month + 1, 1);
              const endOfMonth = new Date(startOfNextMonth);
              endOfMonth.setDate(startOfNextMonth.getDate() - 1);
              picker.$emit('pick', [startOfMonth, endOfMonth]);
            }
          }, {
            text: '本年',
            onClick(picker) {
              const now = new Date();
              // 获取当前年份
              const year = now.getFullYear();
              // 计算本年第一天的日期（1月1日）
              const startOfYear = new Date(year, 0, 1);
              // 计算本年最后一天的日期（12月31日）
              const endOfYear = new Date(year, 11, 31);
              picker.$emit('pick', [startOfYear, endOfYear]);
            }
          }]
        },
        props:{multiple: true,label:'value',value:'label',emitPath:false},
        list1:[],
        listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
        count1:0,
        listLoading1:false,
        "enableAllNum": 0, //可用库存量
        "stockAllNum": 0, //实际库存量
        "unSendAllNum": 0, //未出库数量
        "unStockInAllNum": 0, //未入库数量
        "averagePriceAll": 0, //平均价
        "unFinishedOrderCount": 0, //未入库完成采购订单数
        "unPaidOrderCount": 0, //未付款采购订单数
        "partPaidOrderCount": 0, //部分付款采购订单数
        "partInStockNum": 0, //部分采购入库量
        "stockAllAmount": 0, //实际库存金额
        "lossAllAmount": 0, //亏损金额


        listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
        saleSum:null,

        listQuery3: JSON.parse(JSON.stringify(defaultListQuery3)),
        saleTarget:null,

        listQuery4: JSON.parse(JSON.stringify(defaultListQuery4)),
        curIndex4:1,
        resizeObserver:null,
        myChart:null,
        radio:'1',
        xKey:"",
        targetName:"",
        actualName:"",
        completionName:"",
        chartLoading:false
      }
    },
    props: {
      userList: {
        type: Array,
        default: () => []
      },
      classList:{
        type: Array,
        default: () => []
      },
      goodsList:{
        type: Array,
        default: () => []
      },
    },
    filters: {



    },
    created(){
      if(this.myStockListAnalysis){
        this.listQuery1.tab = 'my'
      }else if(this.allStockListAnalysis){
        this.listQuery1.tab = 'all'
      }
      if(this.pMySaleOrderSummary){
        this.listQuery2.tab = 'my'
      }else if(this.pAllSaleOrderSummary){
        this.listQuery2.tab = 'all'
      }

      if(this.pMySaleTargetSummary){
        this.listQuery3.tab = 'my'
      }else if(this.pAllSaleTargetSummary){
        this.listQuery3.tab = 'all'
      }

      if(this.pUserOrderNumAnalysis){
        this.curIndex4 = 1
      }else if(this.pUserProfitAnalysis){
        this.curIndex4 = 2
      }else {
        this.curIndex4 = 3
      }
      this.listQuery4.month = formatDate(new Date(), 'yyyy-MM')
      // console.log(this.listQuery2)
      this.getList1();
      this.getSaleSum()
      this.getSaleTarget()
      this.$nextTick(()=>{
        this.getChartsData()
        // 智能响应式方案
        const elements = document.querySelectorAll('.charts-div');
        this.resizeObserver = new ResizeObserver(entries => {
          entries.forEach(entry => {
            if(entry.target.id == 'myChart'){
              this.myChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }
          })
        });
        elements.forEach(el => {
          this.resizeObserver.observe(el);
        });
      })

    },

    beforeDestroy() {
      if (this.resizeObserver) {
        const elements = document.querySelectorAll('.charts-div');
        elements.forEach(el => {
          this.resizeObserver.unobserve(el);
        });
        this.resizeObserver.disconnect();
        this.myChart.dispose();
      }
    },
    components:{

    },
    computed:{
      myStockListAnalysis() {
        if(this.roles.indexOf("myStockListAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      allStockListAnalysis() {
        if(this.roles.indexOf("allStockListAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      pMySaleOrderSummary() {
        if(this.roles.indexOf("pMySaleOrderSummary") != -1){
          return true
        }else{
          return false
        }
      },
      pAllSaleOrderSummary() {
        if(this.roles.indexOf("pAllSaleOrderSummary") != -1){
          return true
        }else{
          return false
        }
      },
      pMySaleTargetSummary() {
        if(this.roles.indexOf("pMySaleTargetSummary") != -1){
          return true
        }else{
          return false
        }
      },
      pAllSaleTargetSummary() {
        if(this.roles.indexOf("pAllSaleTargetSummary") != -1){
          return true
        }else{
          return false
        }
      },
      pUserOrderNumAnalysis() {
        if(this.roles.indexOf("pUserOrderNumAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      pUserProfitAnalysis() {
        if(this.roles.indexOf("pUserProfitAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
    },
    methods: {
      formatProgress(percentage){
        return `${percentage}%`
      },
      topage(type,params){
        let routeData
        switch (type){
          case 'searchStock' :
             routeData = this.$router.resolve({name:'searchStock',query:{dataGoodsClass:this.listQuery1.goodsClass,dataKingGoodsId:this.listQuery1.kingGoodsId}});
            break;
          case 'purchaseContract' :
            routeData = this.$router.resolve({name:'purchaseContract',query:{dataTab:this.listQuery1.tab,dataGoodsClass:this.listQuery1.goodsClass,dataKingGoodsId:this.listQuery1.kingGoodsId,dataGoodsInState:[0,1]}});
            break;
          case 'purchaseContract0' :
            routeData = this.$router.resolve({name:'purchaseContract',query:{dataTab:this.listQuery1.tab,dataGoodsClass:this.listQuery1.goodsClass,dataKingGoodsId:this.listQuery1.kingGoodsId,dataPayState:0}});
            break;
          case 'purchaseContract1' :
            routeData = this.$router.resolve({name:'purchaseContract',query:{dataTab:this.listQuery1.tab,dataGoodsClass:this.listQuery1.goodsClass,dataKingGoodsId:this.listQuery1.kingGoodsId,dataPayState:1}});
            break;
          case 'pUserSaleNumAnalysis' :
            routeData = this.$router.resolve({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:this.listQuery4.goodsClass,dataBrandName:this.listQuery4.brandName,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
          case 'pGoodsSaleNumAnalysis' :
            routeData = this.$router.resolve({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:params,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
        }
        window.open(routeData.href);
      },
      changeTab4(index){
        this.curIndex4 = index
        this.listQuery4 = JSON.parse(JSON.stringify(defaultListQuery4))
        this.listQuery4.month = formatDate(new Date(), 'yyyy-MM')
        this.radio = '1'
        this.myChart.clear()
        this.getChartsData()
      },
      //获取图表数据
      getChartsData(){
        let fn
        this.listQuery4.brandName = this.listQuery4.goodsClass ? this.listQuery4.brandName : ''
        let listQuery4 = JSON.parse(JSON.stringify(this.listQuery4))
        listQuery4.userIds = listQuery4.userIds.join(",")
        this.chartLoading = true
        if(this.curIndex4 == 1){
          fn = puserOrderNumAnalysis
          this.xKey = "userRealName"
          this.targetName = "orderNumTarget"
          this.actualName = "orderNumActual"
          this.completionName = "orderNumDiffRate"
        }else if(this.curIndex4 == 2 && this.radio == 1){
          this.xKey = "userRealName"
          this.targetName = 'perShipProfitTarget'
          this.actualName = "perShipProfitActual"
          this.completionName = 'perShipProfitDiffRate'
          fn = puserPerProfitAnalysis
        }else if(this.curIndex4 == 2 && this.radio == 2){
            this.xKey = "userRealName"
            this.targetName = 'shipProfitTarget'
            this.actualName = "shipProfitActual"
            this.completionName = 'shipProfitDiffRate'
            fn = puserProfitAnalysis
        }else if(this.curIndex4 == 4 && this.radio == 1){
          this.xKey = "className"
          this.targetName = 'shipPerProfitTarget'
          this.actualName = "shipPerProfitActual"
          this.completionName = 'shipPerProfitDiffRate'
          delete listQuery4.goodsClass
          delete listQuery4.brandName
          fn = pclassPerProfitAnalysis
        }else if(this.curIndex4 == 4 && this.radio == 2){
          this.xKey = "className"
          this.targetName = 'shipProfitTarget'
          this.actualName = "shipProfitActual"
          this.completionName = 'shipProfitDiffRate'
          fn = pclassProfitAnalysis
          delete listQuery4.goodsClass
          delete listQuery4.brandName
        }else if(this.curIndex4 == 3){
          this.xKey = "className"
          this.targetName = "orderNumTarget"
          this.actualName = "orderNumActual"
          this.completionName = "orderNumDiffRate"
          fn = pclassOrderNumAnalysis
          delete listQuery4.goodsClass
          delete listQuery4.brandName
        }

        fn(listQuery4).then((res)=>{
          this.chartLoading = false
          // if(this.curIndex4 == 1 || this.curIndex4 == 3){
          //   this.drawCharts(res)
          // }else{
          //   this.drawCharts2(res)
          // }
          this.drawCharts(res)

        })
      },
      changeTab3(tab){
        this.listQuery3 = JSON.parse(JSON.stringify(defaultListQuery3))
        this.listQuery3.tab = tab
        this.getSaleTarget()
      },
      //获取销售目标达成
      getSaleTarget(){
        let listQuery3 = JSON.parse(JSON.stringify(this.listQuery3));
        listQuery3.userIds = listQuery3.userIds.join(",")
        psaleTargetSummary(listQuery3).then((res)=>{
          this.saleTarget = res
        })
      },

      changeTab2(tab){
        this.listQuery2 = JSON.parse(JSON.stringify(defaultListQuery2))
        this.listQuery2.tab = tab
        this.getSaleSum()
      },
      //获取销售情况统计
      getSaleSum(){
        let listQuery2 = JSON.parse(JSON.stringify(this.listQuery2));
        listQuery2.userIds = listQuery2.userIds.join(",")
        psaleOrderSummary(listQuery2).then((res)=>{
            this.saleSum = res
        })
      },
       //获取本月时间
      getMonth(){
        const now = new Date();
        // 获取当前月份和年份
        const month = now.getMonth();
        const year = now.getFullYear();
        // 计算本月第一天的日期
        const startOfMonth = new Date(year, month, 1);
        // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
        const startOfNextMonth = new Date(year, month + 1, 1);
        const endOfMonth = new Date(startOfNextMonth);
        endOfMonth.setDate(startOfNextMonth.getDate() - 1);
        return [formatDate(new Date(startOfMonth), 'yyyy-MM-dd'),formatDate(new Date(endOfMonth), 'yyyy-MM-dd')]
      },


      //切换订单执行
      changeTab1(tab){
        this.listQuery1 = JSON.parse(JSON.stringify(defaultListQuery))
        this.listQuery1.tab = tab
        this.handleSearchList1()
      },


      handleSearchList1(){
        this.getList1();
      },

      //获取订单执行情况
      getList1() {
        this.listLoading1 = true;
        this.listQuery1.brandName = this.listQuery1.goodsClass ? this.listQuery1.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
        listQuery.userIds = listQuery.userIds.join(",")
        stockListAnalysis(listQuery).then(response => {
          this.list1 = response.list;
          this.listLoading1 = false;
          this.enableAllNum = response.enableAllNum
          this.stockAllNum = response.stockAllNum
          this.unSendAllNum = response.unSendAllNum
          this.unStockInAllNum = response.unStockInAllNum
          this.averagePriceAll = response.averagePriceAll
          this.unFinishedOrderCount = response.unFinishedOrderCount
          this.unPaidOrderCount = response.unPaidOrderCount
          this.partPaidOrderCount = response.partPaidOrderCount
          this.partInStockNum = response.partInStockNum
          this.stockAllAmount = response.stockAllAmount
          this.lossAllAmount = response.lossAllAmount
        }).catch(()=>{
          this.listLoading1 = false;
        });
      },

      drawCharts(data){
        this.myChart = echarts.init(document.getElementById('myChart'),null,{renderer: 'canvas',useDirtyRect: false});
        // 假设我们有目标销量和实际销量的数据
        let salesData = data

        // 准备数据
        let categories = salesData.map(item => item[this.xKey]);  //x轴
        let targetSales = salesData.map(item => item[this.targetName]);//目标数量
        let actualSales = salesData.map(item => item[this.actualName]);//实际数量
        let differences = salesData.map(item => Number((item[this.actualName] - item[this.targetName]).toFixed(3))*1);//差异值
        let completion = salesData.map(item => item[this.completionName]); //完成率

        // 确定每个项目哪个销量更高
        let isActualHigher = salesData.map(item => item[this.actualName] >= item[this.targetName]);  //是否超过目标

        let higherSalesIndexes = [];
        let lowerSalesValues = [];
        let lineColors = [];
        targetSales.forEach((target, index) => {
          let diff = actualSales[index] - target;
          lineColors.push(diff > 0 ? 'green' : 'red');
          if (actualSales[index] > target) {
            higherSalesIndexes.push(index);
            lowerSalesValues.push(target);
          } else {
            higherSalesIndexes.push(-1); // 标记为无对应高销量
            lowerSalesValues.push(actualSales[index]);
          }
        });
        const minShowItems = 15; // 触发滚动的最小数据量
        let yName,y1Name,y2Name,lineName
        let unit = this.curIndex4 == 1 || this.curIndex4 == 3 ? '吨' : '元'
        if(this.curIndex4 == 1 || this.curIndex4 == 3){
          yName = '目标销量'
          y1Name = '实际销量'
          y2Name = '销量差额'
          lineName = '销量'
        }else if(this.radio == 1){

          yName = '目标吨毛利'
          y1Name = '实际吨毛利'
          y2Name = '吨毛利差额'
          lineName = '吨毛利'
        }else if(this.radio == 2){
          yName = '目标总毛利'
          y1Name = '实际总毛利'
          y2Name = '总毛利差额'
          lineName = '毛利'
        }

         let option = {
            tooltip: {
              trigger: 'axis',
              backgroundColor:'none',
              formatter: function(params) {
                let diff =Number((params[1].value-params[0].value).toFixed(3))*1
                let color = '#000000'
                if(params[1].value-params[0].value >= 0){
                  diff = '↑ '+Math.abs(diff)+unit
                  color = 'green'
                }else{
                  color = 'red'
                  diff = '↓ '+Math.abs(diff)+unit
                }
                let html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  <div style="color:#8b8b8b;font-size: 14px;">${yName}：<span style="color:#6084f2;font-weight: bold">${params[0].value}${unit}</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">${y1Name}：<span style="color:#ffc27b;font-weight: bold">${params[1].value}${unit}</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">${y2Name}：<span style="color:${color};font-weight: bold">${diff}</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">完成率：<span style="color:#ef915d;font-weight: bold">${params[2].value}%</span></div>
                  </div>`;
                return html;
              }
            },
            legend: {
              data: [yName, y1Name,'完成率'],
              textStyle: {
                fontSize: 14 // 设置字体大小为16
              },
              orient: 'horizontal',
              x: '50%',        // 水平起点为容器宽度的15%
              y: 20,           // 垂直起点50px
            },
           grid: {
             left: 50,          // 左侧留空比例
             right: 30,          // 右侧留空
             bottom:30,
             top:80,
             containLabel: true,   // 确保标签不被截断
           },
           dataZoom: [
             {
               type: 'slider',      // 滑动条型dataZoom（必须声明）
               height: 10,           // 滚动条高度
               bottom:16,
               show: salesData.length > minShowItems,          // 默认显示
               xAxisIndex: 0,       // 控制第一个xAxis
               zoomLock: true,        // 禁止缩放（仅滚动）
               start: 0,
               end: Math.min(100, (minShowItems / salesData.length) * 100), // 动态计算初始窗口
             }
           ],
            xAxis: {
              type: 'category',
              data: categories,
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 14,        // 字体大小
              },
              axisTick: {
                show: false,          // 显示刻度线
              },
            },
            yAxis: [
              {
                type: 'value',
                name: lineName,
                nameTextStyle:{
                  color:'#898989'
                },
                position: 'left',
                axisLine: {
                  lineStyle: {
                    color: '#dadada', // X轴轴线颜色
                  }
                },
                axisLabel: {
                  color: '#818181',       // 字体颜色
                  fontSize: 10,        // 字体大小
                },
                splitLine: {
                  show: true,                    // 需手动开启
                  lineStyle: {
                    color: '#ebebeb',  // 半透明细线
                    width: 0.5
                  }
                }
              },
              {
                type: 'value',
                name: '完成率',
                nameTextStyle:{
                  color:'#898989'
                },
                position: 'right',
                axisLine: {
                  lineStyle: {
                    color: '#dadada', // X轴轴线颜色
                  }
                },
                axisLabel: {
                  color: '#818181',       // 字体颜色
                  fontSize: 10,        // 字体大小
                },
                splitLine: {
                  show: false,                    // 需手动开启
                }
              },
            ],
            series: [
              {
                name:yName,
                type: 'bar',
                data: targetSales,
                yAxisIndex: 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    { offset: 0, color: '#6084f2' },
                    { offset: 1, color: '#ffffff' }
                  ])
                },
                barWidth:16,
                label: {
                  show: true,
                  position: 'top',
                  color:'red',
                  fontSize:14,
                  offset: [20, 0] ,
                  formatter: function(params) {
                    let diff = differences[params.dataIndex];
                    // 实际比目标小
                    if (!isActualHigher[params.dataIndex]) {
                      return '↓ '+Math.abs(diff)+unit;
                    }
                    return '';
                  }
                }
              },
              {
                name: y1Name,
                type: 'bar',
                data: actualSales,
                yAxisIndex: 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    { offset: 0, color: '#ffc27b' },
                    { offset: 1, color: '#ffffff' }
                  ])
                },
                barWidth:16,
                label: {
                  show: true,
                  position: 'top',
                  color:'green',
                  fontSize:14,
                  offset: [-14, 0] ,
                  formatter: function(params) {
                    let diff = differences[params.dataIndex];
                    // 实际比目标大
                    if (isActualHigher[params.dataIndex]) {
                      return '↑ '+Math.abs(diff)+unit;
                    }
                    return '';
                  }
                }
              },
              {
                name: '完成率',
                type: 'line',
                data: completion,
                yAxisIndex: 1,
                lineStyle: {
                  color: '#ee905c',
                  width: 2,
                },
                symbol: 'emptyCircle',       // 顶点形状（circle/diamond/triangle等）
                symbolSize: 8,         // 顶点大小
                itemStyle: {
                  color: '#ee905c',     // 顶点填充色
                  borderColor: '#ee905c',  // 顶点边框色
                  borderWidth: 1        // 边框粗细
                }
              },
              {
                name: '连接线',
                type: 'custom',
                renderItem: function(params, api) {
                  let categoryIndex = params.dataIndex;
                  let startPoint = api.coord([categoryIndex, lowerSalesValues[categoryIndex]]);
                  let endPoint = api.coord([categoryIndex, Math.max(targetSales[categoryIndex], actualSales[categoryIndex])]);
                  let x1,x2
                  if(isActualHigher[categoryIndex] ){
                    x1 = startPoint[0]-10
                    x2 = endPoint[0]-10
                  }else{
                    x1 = startPoint[0]+10
                    x2 = endPoint[0]+10
                  }

                  return {
                    type: 'line',
                    shape: {
                      x1: x1,
                      y1: startPoint[1],
                      x2: x2,
                      y2: endPoint[1]
                    },
                    style: api.style({
                      stroke: lineColors[categoryIndex],
                      lineWidth:1
                    })
                  };

                },
                data: higherSalesIndexes.map((index, i) => [i]) // 使用项目的索引作为数据
              },
              {
                name: '连接线3',
                type: 'custom',
                renderItem: function(params, api) {
                  let categoryIndex = params.dataIndex;
                  let startPoint = api.coord([categoryIndex, lowerSalesValues[categoryIndex]]);
                  let endPoint = api.coord([categoryIndex, Math.max(targetSales[categoryIndex], actualSales[categoryIndex])]);
                  let x1,x2
                  if(isActualHigher[categoryIndex] ){
                    x1 = endPoint[0]+2
                    x2 = endPoint[0]-20
                  }else{
                    x1 = endPoint[0]-2
                    x2 = endPoint[0]+20
                  }

                  return {
                    type: 'line',
                    shape: {
                      x1: x1,
                      y1: endPoint[1],
                      x2: x2,
                      y2: endPoint[1]
                    },
                    style: api.style({
                      stroke: '#888888',
                      lineWidth:1
                    })
                  };

                },
                data: higherSalesIndexes.map((index, i) => [i]) // 使用项目的索引作为数据
              }
            ]
          };
        this.myChart.setOption(option);
        this.myChart.on('click', (params)=> {
          if(this.curIndex4 == 1 || this.curIndex4 == 2){
            this.topage('pUserSaleNumAnalysis')
          }else{
            // console.log(params)
            this.topage('pGoodsSaleNumAnalysis',params['name'])
          }

        })
      },

      drawCharts2(data){
        this.myChart = echarts.init(document.getElementById('myChart'),null,{renderer: 'canvas',useDirtyRect: false});
        // 假设我们有目标销量和实际销量的数据
        let salesData = data

        // 准备数据
        let categories = salesData.map(item => item[this.xKey]);  //x轴
        let actualSales = salesData.map(item => item[this.actualName]);//实际数量
        const minShowItems = 15; // 触发滚动的最小数据量
        let yName,lineName
        if(this.radio == 1){
          yName = '实际吨毛利'
          lineName = '吨毛利'
        }else if(this.radio == 2){
          yName = '实际总毛利'
          lineName = '毛利'
        }

        let option = {
          tooltip: {
            trigger: 'axis',
            backgroundColor:'none',
            formatter: function(params) {
              let html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  <div style="color:#8b8b8b;font-size: 14px;">${yName}：<span style="color:#6084f2;font-weight: bold">${params[0].value}元</span></div>
                  </div>`;
              return html;
            }
          },
          legend: {
            data: [yName],
            orient: 'horizontal',
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
            x: '50%',        // 水平起点为容器宽度的15%
            y: 20,           // 垂直起点50px
          },
          grid: {
            left: 50,          // 左侧留空比例
            right: 30,          // 右侧留空
            bottom:30,
            top:80,
            containLabel: true,   // 确保标签不被截断
          },
          dataZoom: [
            {
              type: 'slider',      // 滑动条型dataZoom（必须声明）
              height: 10,           // 滚动条高度
              bottom:16,
              show: salesData.length > minShowItems,          // 默认显示
              xAxisIndex: 0,       // 控制第一个xAxis
              zoomLock: true,        // 禁止缩放（仅滚动）
              start: 0,
              end: Math.min(100, (minShowItems / salesData.length) * 100), // 动态计算初始窗口
            }
          ],
          xAxis: {
            type: 'category',
            data: categories,
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 14,        // 字体大小
            },
            axisTick: {
              show: false,          // 显示刻度线
            },
          },
          yAxis: [
            {
              type: 'value',
              name: lineName,
              nameTextStyle:{
                color:'#898989'
              },
              position: 'left',
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 10,        // 字体大小
              },
              splitLine: {
                show: true,                    // 需手动开启
                lineStyle: {
                  color: '#ebebeb',  // 半透明细线
                  width: 0.5
                }
              }
            }
          ],
          series: [
            {
              name:yName,
              type: 'bar',
              data: actualSales,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#6084f2' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
            }


          ]
        };
        this.myChart.setOption(option);
        this.myChart.on('click', (params)=> {
          if(this.curIndex4 == 1 || this.curIndex4 == 2){
            this.topage('userSaleNumAnalysis')
          }else{
            // console.log(params)
            this.topage('goodsSaleNumAnalysis',params['name'])
          }

        })
      },

    }
  }
</script>


